﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DTO;
namespace Publisher_WS
{
    [Serializable]
    public class GioHang
    {
        List<SachTrongGio> danhSachSach;
        
        public List<SachTrongGio> DanhSachSach
        {
            get { return danhSachSach; }
            set { danhSachSach = value; }
        }

        public GioHang()
        {
            danhSachSach = new List<SachTrongGio>();            
        }

        public decimal TinhTongTien()
        {
            decimal tong = danhSachSach.Sum(s => (s.SoLuong * s.DonGia));
            return tong;
        }

        public int ThemSach(int maSach, int soLuong, string sID)
        {
            Sach sach;
            try
            {
                sach = DataProvider.entities
                                  .Saches
                                  .Where(s => (s.MaSach == maSach))
                                  .Single();
            }
            catch (Exception)
            {
                return WsMessage.DATMUA_SACHKHONGCO;
            }
            
            try
            {
                SachTrongGio stg = danhSachSach
                                    .Where(s => s.MaSach == maSach)
                                    .First();
                
                if(sach.SoLuongCon > soLuong + stg.SoLuong)
                {
                    stg.SoLuong += soLuong;
                    PhieuMua pm =
                        DataProvider.entities
                        .PhieuMuas
                        .Where(phmua => (phmua.sID.CompareTo(sID) == 0 && phmua.MaSach == maSach)).Single();
                    pm.SoLuong = stg.SoLuong;
                    DataProvider.entities.SaveChanges();
                    return WsMessage.DATMUA_OK;
                }
                else
                {
                    return WsMessage.DATMUA_HETSACH;
                }
            }
            catch
            {
                SachTrongGio stgMoi = new SachTrongGio(maSach, soLuong);
                if(sach.SoLuongCon >= stgMoi.SoLuong)
                {
                    danhSachSach.Add(stgMoi);
                    PhieuMua pm = new PhieuMua();
                    pm.sID = sID;
                    pm.MaSach = stgMoi.MaSach;
                    pm.SoLuong = stgMoi.SoLuong;
                    pm.ThanhTien = stgMoi.SoLuong*stgMoi.DonGia;
                    DataProvider.entities.PhieuMuas.AddObject(pm);
                    DataProvider.entities.SaveChanges();
                    return WsMessage.DATMUA_OK;
                }
                else
                {
                    return WsMessage.DATMUA_HETSACH;
                }

            }
                       
        }
    }
}